package cn.hxth.dubbo.service.impl;

import cn.hxth.api.model.ProductName;
import cn.hxth.api.service.IProductNameService;
import cn.hxth.dubbo.service.mapper.ProductNameMapper;
import cn.hxth.dubbo.service.mq.RabbitMQSender;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class ProductNameServiceImpl implements IProductNameService {
    @Resource
    private ProductNameMapper productNameMapper ;
    @Resource
    private RabbitMQSender rabbitMQSender ;
    @Resource(name = "myRedisTemplate")
    private  RedisTemplate<String,Object> redisTemplate ;
    @Override
    public boolean insertProductName(ProductName productName) {
       boolean flag = this.productNameMapper.insert(productName) ;

       if(flag){
           this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"add\", \"data_type\": \"product_name\", \"nid\": " + productName.getNid() +   "}");
       }

        return  flag ;
    }



    @Override
    public boolean deleteProductName(int nid) {
        boolean flag = this.productNameMapper.deleteByPrimaryKey(nid) ;

        if(flag){
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"delete\", \"data_type\": \"product_name\", \"nid\": " + nid +   "}");
        }

        return  flag ;

    }

    @Override
    public List<ProductName> findAll() {
        List<ProductName> productNameList = null;
        List<Object> list = this.redisTemplate.opsForHash().values("nameList");
        if (list == null||list.size()==0) {
            productNameList = this.productNameMapper.selectAll();
            for (ProductName name : productNameList) {

                this.redisTemplate.opsForHash().put("nameList", "name_" + name.getNid(), JSONObject.toJSONString(name));
            }
        } else {
            System.out.println("productNameList数据由redis中读取");
            productNameList = new ArrayList<>();
            for (Object object : list) {
                String jsonStr = (String) object;
                productNameList.add(JSONObject.parseObject(jsonStr, ProductName.class));
            }
        }
        return productNameList;

    }

    @Override
    public ProductName getProductName(int nid) {
        String jsonStr = (String) (this.redisTemplate.opsForHash().get("nameList", "name_" + nid)) ;
        ProductName productName = null ;
System.out.println(jsonStr);
        if(jsonStr==null) {
            productName = this.productNameMapper.selectByPrimaryKey(nid);
            System.out.println(productName);
            this.redisTemplate.opsForHash().put("nameList","name_"+nid,JSONObject.toJSONString(productName));
        }else{
            productName = JSONObject.parseObject(jsonStr,ProductName.class) ;
        }
        return  productName ;
    }
}
